import { defineStore } from "pinia";
import { ElLoading } from "element-plus";
import { store } from "../utils";
import { readonly, ref } from "vue";
import { useUserStoreHook } from "./user";

export const useLunchStore = defineStore("pure-lunch", () => {
  // 是否在线
  const isOnline = ref<boolean>(navigator.onLine);
  // 是否激活
  const isWindowActive = ref<boolean>(true);
  // 当前平台
  const platform = ref<NodeJS.Platform | "browser">();

  const updateOnlineStatus = () => {
    isOnline.value = navigator.onLine;
  };

  // 初始化
  const init = () => {
    if (!platform.value) {
      platform.value = window.platform ?? "browser";

      // 监听浏览器原生的 online/offline 事件，实时更新
      window.addEventListener("online", updateOnlineStatus);
      window.addEventListener("offline", updateOnlineStatus);

      // 定时检测，防止事件丢失
      setInterval(updateOnlineStatus, 5000);

      if (window.ipcRenderer) {
        // 当前为桌面端

        // 监听：桌面端窗口关闭事件
        window.ipcRenderer.on("app-closing", () => {
          ElLoading.service({
            lock: true,
            text: "正在退出，请稍候..."
          });
          try {
            // 关闭窗口时自动登出
            useUserStoreHook().logOut();
          } catch {
            //
          }
          // 最后需要通知成功关闭
          window.ipcRenderer.send("app-ready-to-close");
        });

        // 监听激活与失焦状态
        window.ipcRenderer.on("window-focus", () => {
          isWindowActive.value = true;
        });
        window.ipcRenderer.on("window-blur", () => {
          isWindowActive.value = false;
        });
      } else {
        // 当前为浏览器端
        const updateActiveStatus = () => {
          isWindowActive.value = document.visibilityState !== "hidden";
        };

        // 监听 visibilitychange 事件，实时更新窗口激活状态
        document.addEventListener("visibilitychange", updateActiveStatus);

        // 初始化时立即设置一次
        updateActiveStatus();
      }
    }
  };

  // 显示提示
  const showWindowTips = () => {
    if (window.ipcRenderer) window.ipcRenderer.send("flash-taskbar");
  };

  // 打开关于弹窗
  const openAboutPanel = () => {
    if (window.ipcRenderer) window.ipcRenderer.send("open-about-panel");
  };

  return {
    isOnline: readonly(isOnline),
    isWindowActive: readonly(isWindowActive),
    platform: readonly(platform),
    init,
    showWindowTips,
    openAboutPanel
  };
});

export function useLunchStoreHook() {
  return useLunchStore(store);
}
